<script setup lang="ts">
import { onMounted, ref } from "vue";
import CSSBox from "../components/CSSBox.vue";

const TEXT = ref("(ﾟДﾟ≡ﾟдﾟ)!?");

const num = ref(3);

const textDom = ref<HTMLDivElement>();

const random = (min: number, max: number): number => {
  return Math.random() * (max - min) + min;
};

onMounted(() => {
  if (!textDom.value) return;
  //   过滤掉文本与注释
  const strArr = ["#text", "#comment"];
  //遍历子元素
  const domEach = (dom: HTMLElement, fun: (node: HTMLElement) => void) => {
    dom?.childNodes.forEach((ch) => {
      if (!strArr.includes(ch.nodeName) && !/\S/.test(ch!.nodeValue || "")) {
        const node = ch as HTMLElement;
        fun(node);
      }
    });
  };
  // 为元素添加 故障 样式
  const setFaultStyle = () => {
    domEach(textDom.value!, (node) => {
      node.classList.add("onFault");
      node.style.transform = `translate(${Math.random() * 60 - 30}%,${
        Math.random() * 60 - 30
      }%)`;
      const x = Math.ceil(Math.random() * 100);
      const y = Math.ceil(Math.random() * 100);
      const w = Math.ceil(Math.random() * 100);
      const h = Math.ceil(Math.random() * 100);
      node.style.clipPath = `polygon(${x}% ${y}% ,${x + w}% ${y}% ,${x + w}% ${
        y + h
      }% ,${x}% ${y + h}%)`;
    });
  };
  //   移除样式
  const remFaultStyle = () => {
    domEach(textDom.value!, (node) => {
      node.classList.remove("onFault");
      node.style.transform = "";
      node.style.clipPath = "";
    });
  };
  //   持续时间
  const sustain = 2000;
  //   循环间隙
  const delay = sustain + 1000;

  function autoFault() {
    num.value = Math.ceil(random(1,15))
    let timer = setInterval(() => {
      setFaultStyle();
    }, 50);

    setTimeout(() => {
      remFaultStyle();
      clearInterval(timer);
    }, sustain);
  }

  setInterval(() => {
    autoFault();
  }, delay);
  
});
</script>

<template>
  <CSSBox :TYPE="'JS'">
    <div
      ref="textDom"
      class="fault-container w-full h-full flex justify-center items-center"
    >
      <p v-for="() in num" :text="TEXT" class="fault-text">{{ TEXT }}</p>
    </div>
  </CSSBox>
</template>

<style lang="less" scoped>
.fault-container {
  position: relative;
  .fault-text {
    font-size: 3rem;
    font-weight: bold;
    letter-spacing: 0.5rem;
    user-select: none;
    position: absolute;
    white-space: nowrap;
  }
  .onFault {
    &::after,
    &::before {
      content: "" attr(text) "";
      position: absolute;
      left: 0;
      top: 0;
      mix-blend-mode: screen;
    }
    &::after {
      color: red;
      transform: translateX(2%);
    }
    &::before {
      color: blue;
      transform: translateX(-2%);
    }
  }
}
</style>
